
var advsearch = {
    
    numTerms: 0, // current number of search fields - will be set in init function
    maxTerms: 7, // maximum allowed number of search fields
    
    init: function() {
	var fld = document.getElementById("advSearchForm").getElementsByTagName("fieldset")[0];
	advsearch.numTerms = fld.getElementsByTagName("p").length;
	
	// if javascript is enabled, it would be best to default to one search parameter on load
	for( ; advsearch.numTerms > 1; advsearch.numTerms--) {
	    if(fld.getElementsByTagName("p")[advsearch.numTerms - 1].getElementsByTagName("input")[0].getAttribute("value") != "")
		break;
	    fld.removeChild(fld.getElementsByTagName("p")[advsearch.numTerms - 1]);
	}

	// make sure to disable the appropriate buttons so as to prevent user from opening too many search bars
	// or deleting the only remaining search bar
	if(advsearch.numTerms == 1) { // disable the "-" button if there is only 1 row
	    fld.getElementsByTagName("button")[1].setAttribute("disabled", "disabled");
	} else if(advsearch.numTerms >= advsearch.maxTerms) { // remove the last "+" if it is in the final row
	    fld.getElementsByTagName("button")[2*(advsearch.numTerms - 1)].style.display = "none";
	}

	var buttons = document.getElementsByTagName("button");
	for(var i = 0; i < advsearch.numTerms - 1; i++) {  // disable all but the final "+" button
	    buttons[2 * i].setAttribute("disabled", "disabled");
	}
	
	// give the buttons some functionality!
	var func;
	for(var i = 0; i < buttons.length; i++) {
	    //	alert(buttons[i].className);
	    if(buttons[i].className == "add") {
		func = advsearch.addLine;
	    } else if(buttons[i].className == "remove") {
		func = advsearch.removeLine;
	    } else {
		continue;
	    }

	    addEvent(buttons[i], 'click', func);
	}
    },

    addLine: function(evnt) {
	var options = {all: "All", protein: "By Protein", domain: "By Domain", species: "By Species", fulltext: "Full-Text" };
	var maxLength = 36;

	var frm = document.getElementById("advSearchForm");

	// create the paragraph tag that will contain the new form features
	var par = document.createElement("p");
	
	// create the select tag
	var sel =  document.createElement("select");
	setNodeAttribute(sel, "name", "opt" + advsearch.numTerms);

	for(var i in options) {
	    var opt = document.createElement("option");
	    setNodeAttribute(opt, "value", i);
	    opt.appendChild(document.createTextNode(options[i]));
	    sel.appendChild(opt);
	}
	par.appendChild(sel);
	par.appendChild(document.createTextNode(" ")); // to make the inserted <p> appear identical to php generated ones 

	// create the txt box tag
	var txtBox = document.createElement("input");
	setNodeAttribute(txtBox, "type", "text");
	setNodeAttribute(txtBox, "name", "searchParam" + advsearch.numTerms);
	setNodeAttribute(txtBox, "value", "");
	setNodeAttribute(txtBox, "maxlength", maxLength);
	par.appendChild(txtBox);
	par.appendChild(document.createTextNode(" ")); // to make the inserted <p> appear identical to php generated ones 

	// create add button

	var button = document.createElement("button");
	setNodeAttribute(button, "type", "button");
	setNodeAttribute(button, "class", "add");
//	setNodeAttribute(button, "value", "add");
	button.appendChild(document.createTextNode("+"));
	if(advsearch.numTerms + 1 >= advsearch.maxTerms) button.style.display = "none"; // if it is the last allowed one
	addEvent(button, 'click', advsearch.addLine);
	par.appendChild(button);
	par.appendChild(document.createTextNode(" ")); // to make the inserted <p> appear identical to php generated ones 
    
	// create remove button
	button = document.createElement("button")
	setNodeAttribute(button, "type", "button");
	setNodeAttribute(button, "class", "remove");
//	setNodeAttribute(button, "value", "remove");
	button.appendChild(document.createTextNode("-"));
	addEvent(button, 'click', advsearch.removeLine);
	par.appendChild(button);
	par.appendChild(document.createTextNode(" ")); // to make the inserted <p> appear identical to php generated ones 

	// insert new <p> into the form
	frm.getElementsByTagName("fieldset")[0].insertBefore(par, frm.getElementsByTagName("fieldset")[0].getElementsByTagName("p")[advsearch.numTerms-1].nextSibling);
	advsearch.numTerms++;

	// disable previous add button and, if the second search are has been added, enable the disabled remove button
	frm.getElementsByTagName("button")[2 * (advsearch.numTerms - 2)].setAttribute("disabled", "disabled");

	if(advsearch.numTerms == 2) {
	    frm.getElementsByTagName("button")[1].removeAttribute("disabled");
	}
    },
    
    removeLine: function(evnt) {
	evnt = evnt || window.event;

	var targetPar = (evnt.target) ? evnt.target : evnt.srcElement;
	var frm = document.getElementById("advSearchForm");

	// make it impossible to delete the last search box
	if(advsearch.numTerms < 2) {
	    return;
	}


	while(targetPar.nodeType != 1 || targetPar.nodeName != "P") {
	    targetPar = targetPar.parentNode;
	    if(targetPar.parentNode == "BODY") {
		alert("error: could not remove search terms"); // delete this when done with debugging!!!
		return;
	    }
	}

	// remove the search line
	frm.getElementsByTagName("fieldset")[0].removeChild(targetPar);
	advsearch.numTerms--;
	

	// make it impossible to delete the last search box
	if(advsearch.numTerms == 1) { //////////////////////////////////////////
	    frm.getElementsByTagName("button")[1].setAttribute("disabled", "disabled");
	}

	// reactivate the plus box in the leading paragraph
	if(advsearch.numTerms + 1 <= advsearch.maxTerms) {
	    if(advsearch.numTerms + 1 == advsearch.maxTerms) { // display the hidden '+' box
		frm.getElementsByTagName("button")[2 * (advsearch.numTerms-1)].style.display = "";
	    }

	    // enable the now-leading '+' box
	    frm.getElementsByTagName("button")[2 * (advsearch.numTerms-1)].removeAttribute("disabled");
	}

	// rename the fields to properly reflect their cardinality within the list
	var pars = document.getElementById("advSearchForm").getElementsByTagName("fieldset")[0].getElementsByTagName("p");
	for(var i = 0; i < advsearch.numTerms ; i++) {
	    pars[i].getElementsByTagName("select")[0].setAttribute("name", "opt" + i);
	    pars[i].getElementsByTagName("input")[0].setAttribute("name", "searchParam" + i);
	}
    }
}
    
var motifsearch = {
    init: function() {
	var form = document.getElementById("motifSearchForm");
	addEvent(form, 'submit', motifsearch.checkParam);
    },

    /* Check to make sure that the user has entered reasonable parameters in areas of potential confusion */
    checkParam: function(evnt) {
	var stopEvnt = 0;
	var form = document.getElementById("motifSearchForm");
	
	if(!form.motifFormat[0].checked && !form.motifFormat[1].checked) {
	    alert("Please select a file to upload or enter an appropriately formatted string into the text area.")
	    stopEvnt = 1;
	} else if(form.motifFormat[1].checked && (form.motifTextarea.value.length < 5 || form.motifTextarea.value == "Enter Motif Here")) {
	    alert("Please enter a matrix or motif in the text area.")
	    form.motifTextarea.focus();
	    stopEvnt = 1;
	} else if(isNaN(form.motifThreshold.value) || form.motifThreshold.value < 0 || form.motifThreshold.value > 100) {
		alert("Please enter a value between 0 and 100 in the E-score threshold input field.")
		form.motifThreshold.focus();
		stopEvnt = 1;
	} else if(isNaN(form.motifGC.value) || form.motifGC.value <= 0 || form.motifGC.value >= 100) {
		alert("Please enter a value between 0 and 100 in the % GC input field.")
		form.motifGC.focus();
		stopEvnt = 1;
	}

	if(stopEvnt == 1)
	    stopEvent(evnt);
    }
}


// load code for manipulating advanced search options
addEvent(window, 'load', setup_advsearch);

function setup_advsearch() {
    /* initialize the advanced form's javascript */ 
    if(document.getElementById("advSearchForm")) {
	advsearch.init();
	motifsearch.init();
	autoSelectRad();
    }

    /* formats links used for hiding / expanding elements */
    scanlinks();
    
    /* make the search form help links create pop-up windows */
    setupHelpLinks();
}


/* formats links used for hiding / expanding elements */
function scanlinks() {
    var links = document.getElementsByTagName("a");

    // make any link of the "not-link" or "not-link-down" class toggleable
    for(var i = 0 ; i < links.length ; i++) {
	if(links[i].className == "not-link" || links[i].className == "not-link-down") {
	    addEvent(links[i], 'click', toggleDivVis);
	}
    }

    // hide all the linked-to divs on load
    var divs = document.getElementsByTagName("div");
    for(var i = 0; i < divs.length ; i++) {
	if(divs[i].className == "optdiv" || divs[i].className == "pub_downloads") {
	    divs[i].style.display = "none";
	}
    }
}

function toggleDivVis(e) {
    // get event
    var e = e || window.event;

    // find the neighboring div that should have its display toggled
    var dv = this.parentNode

    while(dv.nextSibling && dv.nodeName != "DIV") {
	dv = dv.nextSibling;
    }


    if(dv.nodeName == "DIV") {
	
	// toggle the visibility
	if(dv.style.display == "none") {
	    dv.style.display = "block";
	} else
	    dv.style.display = "none";
	
	// stop the browser from actually following the link
    } else {
	alert("could not find div");
    }

    stopEvent(e);

}


// modified from http://www.futureoftheweb.com/blog/submit-a-form-in-ie-with-enter 
function addInputSubmitEvent(form, input) {
    addEvent(input, 'keydown', function(e) {
        e = e || window.event;
        if (e.keyCode == 13) {
            form.submit();
        }
    });
}


/* got to make the File and Textarea radio buttons get selected whenever their fields *
 * are changed                                                                        */
function autoSelectRad() {
    addEvent(document.motifSearchForm.motifFile, 'change', selectRad)
    addEvent(document.motifSearchForm.motifTextarea, 'change', selectRad)
    addEvent(document.dnaSearchForm.dnaFile, 'change', selectRad)
    addEvent(document.dnaSearchForm.dnaTextarea, 'change', selectRad)
}

function selectRad(e) {
    var e = e || window.event;
    var eTarget = e.target || e.srcElement;

    var form;
    var button;

    if(eTarget == document.motifSearchForm.motifFile)
	document.motifSearchForm.motifFormat[0].checked = true;
    else if(eTarget == document.motifSearchForm.motifTextarea)
	document.motifSearchForm.motifFormat[1].checked = true;
    else if(eTarget == document.dnaSearchForm.dnaFile)
	document.dnaSearchForm.dnaFormat[0].checked = true;
    else if(eTarget == document.dnaSearchForm.dnaTextarea)
	document.dnaSearchForm.dnaFormat[1].checked = true;
}

function setupHelpLinks() {
    var divs = document.getElementsByTagName("div");

    for(var i = 0 ; i < divs.length ; i++) {
	if(divs[i].className == "help") {
	    var tmpa = divs[i].getElementsByTagName("a")[0];
	    if(tmpa) {
		addEvent(tmpa, 'click', function(e) {
		    var e = e || window.event;
		    var target = e.target || e.srcElement;

		    var width;
		    var height;
		    if(target.id == "text_search_help") {
		      width = 500;
		      height = 600;
		    } else if(target.id == "motif_search_help") {
		      width = 900;
		      height = 900;
		    } else if(target.id == "dna_search_help") {
		      width = 900;
		      height = 900;
		    }

		    window.open(target.href, "help", 'width=' + width + ', height=' + height + ', scrollbars=1');
		    stopEvent(e);
		});
	    }

	}

    }

}